package com.chipcoo.shiro.mgt;

import com.chipcoo.IUserPrincipal;
import com.chipcoo.UserPrincipal;
import com.chipcoo.services.UserService;
import com.chipcoo.utils.BeanUtils;
import org.apache.shiro.io.SerializationException;
import org.apache.shiro.io.Serializer;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.SimplePrincipalCollection;

public class PrincipalSerializer implements Serializer<PrincipalCollection> {

    @Override
    public PrincipalCollection deserialize(byte[] serialized) throws SerializationException {
        if (serialized == null) {
            String msg = "argument cannot be null.";
            throw new IllegalArgumentException(msg);
        }
        SimplePrincipalCollection simplePrincipalCollection = new SimplePrincipalCollection();
        String userIDsText = new String(serialized);
        String[] userIDs = userIDsText.split(",");
        for (int i=0;i<userIDs.length;i++){
            Integer userID  = Integer.valueOf(userIDs[i]);
            UserPrincipal principal = BeanUtils.getBean("userService",UserService.class).getPrincipal(userID);
            if(null!=principal)
                simplePrincipalCollection.add(principal,"dbRealm");
        }
        return simplePrincipalCollection;
    }

    @Override
    public byte[] serialize(PrincipalCollection o) throws SerializationException {
        if (o == null) {
            String msg = "argument cannot be null.";
            throw new IllegalArgumentException(msg);
        }
        StringBuilder sb = new StringBuilder();
        o.forEach( principal->{
            if(principal instanceof IUserPrincipal){
                sb.append(((IUserPrincipal) principal).getUserID());
                sb.append(',');
            }
        });
        if(sb.length()>0) sb.deleteCharAt(sb.length()-1);
        return sb.toString().getBytes();
    }
}
